import 'package:flutter_public/flutter_public.dart';

import '../model/data_api_model.dart';
import '../model/test_model.dart';

/// FileName test_list_notifier
///
/// @Author lax
/// @Date 2024/6/4
///
/// @Description

class TestListNotifier extends EasyRefreshNotifier {
  /// 数据源
  List<TestModel> dataSource = [];

  int page = 1;

  int size = 10;

  /// 筛选模型
  late TestModel filterModel;

  TestListNotifier({TestModel? filterModel}) {
    if (filterModel == null) {
      initFilterModel();
    } else {
      this.filterModel = filterModel;
    }
    requestData();
  }

  /// 初始化筛选模型
  void initFilterModel() {
    filterModel = TestModel();
    notifyListeners();
  }

  /// 下拉刷新
  @override
  void refreshData() {
    page = 1;
    requestData();
  }

  /// 上拉加载
  @override
  void loadData() {
    page += 1;
    requestData();
  }

  @override
  Future<void> requestData() async {
    await getToken();
    final resp = await Api.get(
      base: base,
      url: url,
      params: params,
    );
    final result = DataApiModel<List<TestModel>>.fromJson(resp, convertFunc);
    pageStatusChanged(result.success);

    List<TestModel> data = result.data ?? [];
    if (page == 1) {
      dataSource = [];
    }
    dataSource.addAll(data);
    easyRefreshController.finishRefresh();
    easyRefreshController.finishLoad(
        noMore: dataSource.length >= (result.count ?? 0));

    notifyListeners();
  }

  Future<void> deleteAction(TestModel model) async {
    Loading.show();
    final resp = await Api.post(
      base: TestListNotifier.base,
      url: 'api/manage/ap/ApInfo/DeleteAp?APID=${model.id ?? ''}',
    );
    Loading.dismiss();
    if (resp['Code'] == 200) {
      Toast.show('删除成功');
      dataSource.remove(model);
      notifyListeners();
    }
  }

  String get url {
    // return 'api/manage/ap/ApInfo/GetListMini';
    return 'api/manage/ap/ApInfo/GetMyCreatedList';
  }

  Map<String, dynamic> get params {
    Map<String, dynamic> para = {
      'PageIndex': 1,
      'PageSize': 10,
    };
    para.addAll(filterModel.toJson());
    return para;
  }

  List<TestModel> Function(dynamic json)? get convertFunc =>
      (json) => json.map<TestModel>((e) => TestModel.fromJson(e)).toList();

  static String? token;

  static String base = 'https://aksvpotest.ab-inbev.cn:460/';

  static getToken() async {
    if (token != null) {
      return;
    }
    final resp = await Api.post(
      base: base,
      url: 'api/base/check/login',
      params: {
        'Account': '28068686',
        'Password': '9',
      },
    );
    if (resp['Token'] != null) {
      token = resp['Token'];
      Api.headers['X-Token'] = token;
    }
  }
}
